# permission_dao.py
from sqlalchemy.orm import Session
from ..do.permission_do import PermissionModel


def getPermission(db: Session, permission_id: str):
    return db.query(PermissionModel).filter(PermissionModel.id == permission_id).first()

def getPermissionList(db: Session):
    return db.query(PermissionModel).all()

def getPermissions(db: Session, parent_id: str = None, skip: int = 0, limit: int = 100):
    query = db.query(PermissionModel)
    if parent_id is None:
        query = query.filter(PermissionModel.parent_id.is_(None))
    else:
        query = query.filter(PermissionModel.parent_id == parent_id)
    return query.offset(skip).limit(limit).all()


def getAllPermissions(db: Session):
    return db.query(PermissionModel).all()


def createPermission(db: Session, permission):
    permissionModel = PermissionModel(**permission)
    db.add(permissionModel)
    db.commit()
    db.refresh(permissionModel)
    return permissionModel


def updatePermission(db: Session, permission_id: str, permission):
    permissionModel = getPermission(db, permission_id)
    if permissionModel is None:
        return None
    for key, value in permission.items():
        setattr(permissionModel, key, value)
    db.commit()
    db.refresh(permissionModel)
    return permissionModel


def deletePermission(db: Session, permission_id: str):
    permissionModel = getPermission(db, permission_id)
    if permissionModel is None:
        return False
    db.delete(permissionModel)
    db.commit()
    return True

def get_by_name(db: Session, name: str):
    return db.query(PermissionModel).filter(PermissionModel.name == name).first()

def get_by_path(db: Session, path: str):
    return db.query(PermissionModel).filter(PermissionModel.endpoint == path).first()
